package cl.gob.minvu.catastromobile.util;

import java.io.ByteArrayOutputStream;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONObject;

import com.google.gson.Gson;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Base64;
import android.view.inputmethod.InputMethodManager;

/**
 * @author psep
 * 
 */
public final class GenericUtil {

	private static final Logger logger = Logger.getLogger(GenericUtil.class);

	public static final String SESSION = "Catastro";
	public static final String DB_NAME = "Catastro.db";

	public static final String FICHA = "ficha";
	public static final String GRUPO_PRINCIPAL = "mainGroup";
	public static final String ENCUESTADO = "encuestado";
	public static final String DIRECCION = "direccion";
	public static final String DIAGNOSTICO = "diagnostico";
	public static final String LIST_SECUNDARIO = "listSecundario";
	public static final String GRUPO_SECUNDARIO = "grupoSecundario";
	public static final String OBSERVACIONES = "observaciones";
	public static final String SITUACION = "situacion";
	public static final String EVALUACION = "evaluacion";
	public static final String PHOTO_TMP = "photo_tmp";
	public static final String PHOTO_1 = "photo1";
	public static final String PHOTO_2 = "photo2";
	public static final String PHOTO_3 = "photo3";
	public static final String PHOTO_4 = "photo4";

	/**
	 * @param a
	 * @return
	 */
	public static final int stringToInt(String a) {
		try {
			if (a == null) {
				return 0;
			} else {
				a = a.trim();

				if (a.equals("")) {
					return 0;
				} else {
					return Integer.parseInt(a);
				}
			}
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * @param activity
	 */
	public static final void hideKeyboard(Activity activity) {
		if (activity != null && activity.getWindow() != null
				&& activity.getWindow().getDecorView() != null) {
			InputMethodManager imm = (InputMethodManager) activity
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(activity.getWindow().getDecorView()
					.getWindowToken(), 0);
		}
	}

	/**
	 * @param activity
	 * @return
	 */
	public static final boolean isConnected(Activity activity) {
		ConnectivityManager connMgr = (ConnectivityManager) activity
				.getSystemService(Activity.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @param run
	 * @param dv
	 * @return
	 */
	public static final boolean validateRun(int run, char dv) {
		if (run < 10000 || run >= 50000000) {
			return false;
		}

		int m = 0, s = 1;

		for (; run != 0; run /= 10) {
			s = (s + run % 10 * (9 - m++ % 6)) % 11;
		}

		return dv == (char) (s != 0 ? s + 47 : 75);
	}

	/**
	 * @param date
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public static final String dateToString(Date date) {
		Format formatter = new SimpleDateFormat("dd/MM/yyyy");
		return formatter.format(date);
	}

	/**
	 * @param activity
	 * @return
	 */
	public static final boolean isDeviceSupportCamera(Activity activity) {
		if (activity.getApplicationContext().getPackageManager()
				.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @param bitmap
	 * @return
	 */
	public static final String bitmapToString(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		byte[] b = baos.toByteArray();
		String temp = Base64.encodeToString(b, Base64.DEFAULT);
		return temp;
	}

	/**
	 * @param encodedString
	 * @return
	 */
	public static final Bitmap stringToBitMap(String encodedString) {
		try {
			byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
			Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
					encodeByte.length);
			return bitmap;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	/**
	 * @param session
	 * @param key
	 * @param className
	 * @return
	 */
	public static final <T> Object jsonToObject(SharedPreferences session,
			String key, Class<T> className) {
		String json = session.getString(key, null);
		Object object = null;

		if (json != null) {
			object = new Gson().fromJson(json, className);
		}

		return object;
	}

	/**
	 * @param plain
	 * @return
	 */
	public static final String encode(String plain) {
		String encryptText = null;
		byte[] bytesEncode = plain.getBytes();
		encryptText = Base64.encodeToString(bytesEncode, Base64.DEFAULT);

		return encryptText;
	}

	/**
	 * @param encrypt
	 * @return
	 */
	public static final String decode(String encrypt) {
		String plainText = null;
		byte[] bytesDecode = Base64.decode(encrypt, Base64.DEFAULT);
		plainText = new String(bytesDecode);

		return plainText;
	}

	/**
	 * @param json
	 * @param key
	 * @return
	 */
	public static final Object getFieldByJSON(JSONObject json, String key) {
		try {
			return json.get(key);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * @param mBitmap
	 * @param newWidth
	 * @param newHeigth
	 * @return
	 */
	public static final Bitmap redimensionarImagenMaximo(Bitmap mBitmap, float newWidth,
			float newHeigth) {
		int width = mBitmap.getWidth();
		int height = mBitmap.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeigth) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		
		return Bitmap.createBitmap(mBitmap, 0, 0, width, height, matrix, false);
	}

}
